<script setup>
import requestUtil, {getServerUrl} from '@/utils/request'
import {onBeforeUnmount, onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import Cookies from "js-cookie";
import {encrypt, decrypt} from "@/utils/jsencrypt";
import router from '@/router';
import store from "@/store";
import {useToggle} from "@vueuse/core";

const loginForm = ref({
  username: '',
  password: '',
  code: '',
  emailCode: '',
  rememberMe: false,
})

const loginRules = {
  username: [{required: true, trigger: "blur", message: "请输入您的账号"}],
  password: [{required: true, trigger: "blur", message: "请输入您的密码"}]
};

const loginRef = ref(null)
loginRef.value = undefined;

let codeUrl = ref('')

const twoAuthStatus = ref(0)

const isCountingDown = ref(false);
const countdown = ref(60);
const buttonText = ref('获取邮箱验证码');
let timer = null;


const getCodeImg = async () => {
  const res = await requestUtil.get('user/code');
  codeUrl.value = "data:image/png;base64," + res.data;
}

const startCountdown = () => {
  isCountingDown.value = true;
  countdown.value = 60;
  buttonText.value = `倒计时 ${countdown.value}s`;

  timer = setInterval(() => {
    countdown.value--;
    buttonText.value = `倒计时 ${countdown.value}s`;

    if (countdown.value <= 0) {
      clearInterval(timer);
      isCountingDown.value = false;
      buttonText.value = '获取邮箱验证码';
    }
  }, 1000);
};

const getEmailCode = async () => {
  let res = await requestUtil.post('user/email/code', loginForm.value)
  let data = res.data
  if (data.code === 200) {
    loginForm.value.emailCode = data.msg
    startCountdown()
  } else {
    ElMessage.error(data.msg)
  }
}

const initAuthStatus = async () => {
  let res = await requestUtil.get('user/update/two/auth')
  let data = res.data
  if (data.code === 200) {
    twoAuthStatus.value = data.msg
    if (twoAuthStatus.value === 0) {
      await getCodeImg()
    }
  } else {
    ElMessage.error(data.msg)
  }
}
initAuthStatus()

const handleLogin = () => {
  loginRef.value.validate(async (valid) => {
    if (valid) {
      let result = await requestUtil.post("user/login", loginForm.value);
      let data = result.data;
      if (data.code === 200) {

        Cookies.set('token', data.token)

        let res = await requestUtil.get("user/login");
        let getData = res.data;
        if (getData.code === 200) {
          localStorage.setItem("menuList", JSON.stringify(getData.msg))
        } else {
          ElMessage.error(getData.msg)
          Cookies.remove('token')
          return
        }

        //获取登陆用户所属角色
        const currentUser = data.user
        currentUser.roles = data.roles
        localStorage.setItem("currentUser", JSON.stringify(currentUser))
        const imgUrl = ref(getServerUrl() + 'media/userAvatar/' + currentUser.avatar)

        localStorage.setItem("imgUrl", imgUrl.value)

        Cookies.set('username', loginForm.value.username, {expires: 30});

        //勾选了后，在cookie中设置记住用户名和密码
        if (loginForm.value.rememberMe) {
          Cookies.set('password', encrypt(loginForm.value.password), {expires: 30});
          Cookies.set('rememberMe', loginForm.value.rememberMe, {expires: 30});
        } else {
          //否则移除
          Cookies.remove('password');
          Cookies.remove('rememberMe');
        }
        ElMessage.success(data.msg);

        //把暗色模式的状态发送store的blackStatus：
        store.commit('SET_BLACK_STATUS', false)
        useToggle(false)
        router.replace('/dashBoard')

      } else {
        ElMessage.error(data.msg)
      }
    } else {
      console.log("验证失败")
    }
  })
}


function getCookie() {
  const username = Cookies.get('username');
  const password = Cookies.get('password');
  const rememberMe = Cookies.get('rememberMe');
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  }
}

getCookie();

onMounted(() => {
  document.documentElement.classList.remove('dark')
})
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<template>
  <div class="login">
    <el-form ref="loginRef" class="login-form" :model="loginForm" :rules="loginRules">
      <h3 class="title">BVCoss运维管理系统</h3>

      <label>用户名：</label>
      <el-form-item size="large" prop="username">
        <el-input v-model="loginForm.username" type="text" size="large" autocomplete="off" placeholder="用户名">
        </el-input>
      </el-form-item>

      <label>密码：</label>
      <el-form-item size="large" prop="password">
        <el-input v-model="loginForm.password" type="password" size="large" autocomplete="off" placeholder="密码">
        </el-input>
      </el-form-item>

      <label v-if="twoAuthStatus === 1">邮箱验证码：</label>
      <el-form-item v-if="twoAuthStatus === 1"
                    size="large"
                    prop="code"
      >
        <el-input v-model="loginForm.emailCode" style="width: 63%" type="text" size="large" autocomplete="off"
                  placeholder="邮箱验证码"></el-input>
        <el-button style="margin: 5px 0 0 10px;"
                   :disabled="isCountingDown"
                   :loading="isCountingDown"
                   type="primary"
                   @click="getEmailCode()">
          {{ buttonText }}
        </el-button>
      </el-form-item>

      <label v-if="twoAuthStatus === 0">验证码：</label>
      <el-form-item v-if="twoAuthStatus === 0" size="large" prop="code">
        <el-input v-model="loginForm.code" style="width: 63%" type="text" size="large" autocomplete="off"
                  placeholder="验证码"></el-input>
        <div class="login-code" style="">
          <img :src="codeUrl" @click="getCodeImg" class="login-code-img" alt="">
        </div>
      </el-form-item>

      <el-checkbox v-model="loginForm.rememberMe" style="margin: 0 0 25px 0">记住密码</el-checkbox>

      <el-form-item style="width: 100%">
        <el-button size="large" type="primary" style="width: 100%" @click.prevent="handleLogin">登 陆</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
a {
  color: white
}

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/img/background.jpeg");
  background-size: cover;
}

.title {
  font-size: 25px;
  font-weight: bold;
  margin: 0 auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: white;
  width: 400px;
  padding: 25px 25px 5px 25px;

  label {
    font-weight: bold;
  }

  .el-input {
    color: black;
    margin-top: 5px;
    height: 40px;

    input {
      display: inline-block;
      height: 40px;
    }


  }

  .login-code {
    width: 35%;
    height: 30px;
    float: right;

    img {
      cursor: pointer;
      vertical-align: middle;
    }
  }

  .login-code-img {
    height: 30px;
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 30%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
}
</style>
